import type { Team } from '@/types'
import type { Ref } from 'vue'

export interface SettingTeam
  extends Pick<Team, 'id' | 'name'> {
  disabled: boolean
}
export function useSettings(
  teams: Ref<Pick<Team, 'id' | 'name'>[]>,
) {
  const [ids, setIds] = useState<Team['id'][]>([])
  const [settingTeams, setSettingTeams] = useState<
    SettingTeam[][]
  >([])

  /**
   * 除当前ID外，其他所有选中的ID对应的团队都不可选
   */
  function checkDisabled(i: number, j: number) {
    const copyIds = [...unref(ids)]
    copyIds.splice(i, 1)

    const team = unref(teams)[j]
    return copyIds.includes(team!.id)
  }

  watchEffect(() => {
    setIds(unref(teams).map(v => v.id))
  })

  watch(
    () => ids.value,
    () => {
      const n = toValue(teams).length
      setSettingTeams(
        Array.from({ length: n }).map((_v, i) =>
          unref(teams).map((team, j) => {
            return {
              ...team,
              disabled: checkDisabled(i, j),
            }
          }),
        ),
      )
    },
    {
      deep: true,
    },
  )

  return {
    settingIds: ids,
    setIds,
    settingTeams,
    setSettingTeams,
  }
}
